package com.myMinistry.gui;

import java.util.ArrayList;
import java.util.HashMap;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.myMinistry.R;
import com.myMinistry.provider.MinistryContract.Literature;
import com.myMinistry.provider.MinistryService;

public class LiteratureListFrag extends ListFragment {
	private static final String MAP_ID = "_id";
	private static final String MAP_TITLE = "title";
	
	private ArrayList<HashMap<String, String>> list;
	private HashMap<String, String> map;
	private SimpleAdapter adapter;
	private MinistryService database;
	private Cursor cursor;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.literature_listfrag, null);
		return view;
	}
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
    	super.onActivityCreated(savedInstanceState);
    	
    	/** Initialize the variables */
    	list = new ArrayList<HashMap<String, String>>();
    	database = new MinistryService(getActivity().getApplicationContext());
    	
    	String[] from = new String[] {MAP_TITLE};
    	int[] to = new int[] {R.id.title};
    	
    	adapter = new SimpleAdapter(getActivity().getApplicationContext(), list, R.layout.default_listview_item, from, to);
    	setListAdapter(adapter);
	}
	
	public void updateList(int literatureTypeID) {
	    list.clear();
	    database.openReadable();
    	/** Get all literature types. */
    	cursor = database.fetchAllLiteratureByType(literatureTypeID);
    	/** Loop over the results */
    	while(cursor.moveToNext()) {
    		map = new HashMap<String, String>();
    		map.put(MAP_ID, cursor.getString(cursor.getColumnIndex(Literature._ID)));
    		map.put(MAP_TITLE, (cursor.getInt(cursor.getColumnIndex(Literature.ACTIVE)) == MinistryService.ACTIVE) ? cursor.getString(cursor.getColumnIndex(Literature.NAME)) : cursor.getString(cursor.getColumnIndex(Literature.NAME)) + " " + getActivity().getString(R.string.inactiveWithPadding));
    		list.add(map);
    	}
    	cursor.close();
    	database.close();
    	adapter.notifyDataSetChanged();
    }
    
    @SuppressWarnings("unchecked")
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		HashMap<String, String> entry = (HashMap<String, String>) l.getItemAtPosition(position);
    	((LiteratureManager) getActivity()).itemTouched(Integer.valueOf(entry.get(MAP_ID)));
    	
    }
}